function applyStatus(status, err){
  const s = status || (err ? 'ERROR' : 'UNKNOWN')
  chrome.storage.local.get(['pluginStatus']).then(st=>{
    const eff = (s === 'NOT_CHROME' && (st.pluginStatus === 'TOPMOST' || st.pluginStatus === 'NOTOPMOST')) ? st.pluginStatus : s
    let text = ''
    if (eff === 'TOPMOST') text = 'TOP'
    else if (eff === 'NOTOPMOST') text = 'OFF'
    else if (eff === 'NO_WINDOW') text = 'NW'
    else if (eff === 'PROCESS_ERROR') text = 'PE'
    else if (err) text = 'ERR'
    else if (eff === 'NOT_CHROME') text = 'NC'
    else text = ''
    chrome.action.setBadgeText({ text })
    chrome.action.setBadgeBackgroundColor({ color: eff === 'TOPMOST' ? '#28a745' : '#6c757d' })
    chrome.storage.local.set({lastStatus:eff})
    setIconTheme(eff === 'TOPMOST')
  })
}

function setPluginStatus(status){
  if (status === 'TOPMOST' || status === 'NOTOPMOST') {
    chrome.storage.local.set({ pluginStatus: status })
  }
}

function toggle(){
  chrome.runtime.sendNativeMessage('com.topmost.chrome_window',{ command: 'toggle' },(response)=>{
    const err = chrome.runtime.lastError?.message
    const s = response?.status
    applyStatus(s, err)
    setPluginStatus(s)
    if (err) console.error(err)
  })
}

chrome.action.onClicked.addListener(()=>{toggle()})

  chrome.runtime.onInstalled.addListener(()=>{
  chrome.storage.local.get(['autoTopEnabled','whitelist','pluginStatus']).then(s=>{
    if(s.autoTopEnabled===undefined) chrome.storage.local.set({autoTopEnabled:true})
    if(!Array.isArray(s.whitelist)) chrome.storage.local.set({whitelist:[]})
    if(!s.pluginStatus) chrome.storage.local.set({pluginStatus:'NOTOPMOST'})
  })
})

chrome.runtime.onMessage.addListener((msg,sender,sendResponse)=>{
  if(msg&&msg.type==='video-state'){
    chrome.storage.local.get(['autoTopEnabled','whitelist']).then(s=>{
      if(!s.autoTopEnabled) return
      const host = msg.host || ''
      const wl = Array.isArray(s.whitelist)?s.whitelist:[]
      const allowed = wl.length===0 || wl.includes(host)
      if(!allowed) return
      const command = msg.state==='play' ? 'set' : 'unset'
      chrome.runtime.sendNativeMessage('com.topmost.chrome_window',{command},(response)=>{
        const err = chrome.runtime.lastError?.message
        applyStatus(response?.status, err)
        if (err) console.error(err)
      })
    })
  }
})

chrome.commands.onCommand.addListener((cmd)=>{ if(cmd==='toggle-topmost') toggle() })

chrome.runtime.onMessage.addListener((msg)=>{
  if(msg&&msg.type==='manual-toggle') toggle()
  if(msg&&msg.type==='manual-set'){
    chrome.runtime.sendNativeMessage('com.topmost.chrome_window',{command:'set'},(response)=>{
      const err = chrome.runtime.lastError?.message
      const s = response?.status
      applyStatus(s, err)
      setPluginStatus(s)
      if (s === 'TOPMOST') {
        chrome.storage.local.set({autoTopEnabled:true})
      }
      if (err) console.error(err)
    })
  }
  if(msg&&msg.type==='manual-unset'){
    chrome.runtime.sendNativeMessage('com.topmost.chrome_window',{command:'unset'},(response)=>{
      const err = chrome.runtime.lastError?.message
      const s = response?.status
      applyStatus(s, err)
      setPluginStatus(s)
      if (s === 'NOTOPMOST') {
        chrome.storage.local.set({autoTopEnabled:false})
      }
      if (err) console.error(err)
    })
  }
  if(msg&&msg.type==='apply-auto-switch'){
    const command = msg.on ? 'set' : 'unset'
    chrome.runtime.sendNativeMessage('com.topmost.chrome_window',{command},(response)=>{
      const err = chrome.runtime.lastError?.message
      applyStatus(response?.status, err)
      if (err) console.error(err)
    })
  }
  if(msg&&msg.type==='pin-toggle'){
    chrome.windows.getCurrent({},(win)=>{
      chrome.storage.local.get(['pinned']).then(s=>{
        const enable = !s.pinned
        chrome.sidePanel.setOptions({ windowId: win.id, path: 'panel.html', enabled: enable }, ()=>{
          if(enable) chrome.sidePanel.open({ windowId: win.id })
          chrome.storage.local.set({ pinned: enable })
        })
      })
    })
  }
})
function syncStatus(){
  chrome.runtime.sendNativeMessage('com.topmost.chrome_window',{command:'query'},(response)=>{
    const err = chrome.runtime.lastError?.message
    applyStatus(response?.status, err)
  })
}
chrome.tabs.onActivated.addListener(()=>{syncStatus()})
chrome.tabs.onUpdated.addListener((tabId,info,tab)=>{ if(info&&info.status==='complete') syncStatus() })
chrome.windows.onFocusChanged.addListener(()=>{ syncStatus() })
chrome.runtime.onInstalled.addListener(()=>{
  chrome.sidePanel.setOptions({ path: 'panel.html', enabled: false })
  chrome.storage.local.get(['pluginStatus']).then(s=>{
    setIconTheme(s.pluginStatus==='TOPMOST')
  })
})
chrome.runtime.onStartup.addListener(()=>{
  chrome.storage.local.get(['pluginStatus']).then(s=>{
    setIconTheme(s.pluginStatus==='TOPMOST')
  })
})

function setIconTheme(isTop){
  function draw(size){
    const c=new OffscreenCanvas(size,size)
    const ctx=c.getContext('2d')
    ctx.fillStyle='#0b1320'
    ctx.fillRect(0,0,size,size)
    const color = isTop ? '#00c853' : '#ff3b30'
    ctx.fillStyle=color
    const r=size*0.38
    ctx.beginPath()
    ctx.arc(size/2,size/2,r,0,Math.PI*2)
    ctx.fill()
    ctx.strokeStyle='#ffffff'
    ctx.lineCap='round'
    ctx.lineJoin='round'
    ctx.lineWidth=Math.max(2,size*0.14)
    ctx.beginPath()
    ctx.moveTo(size*0.52,size*0.62)
    ctx.lineTo(size*0.52,size*0.36)
    ctx.moveTo(size*0.39,size*0.48)
    ctx.lineTo(size*0.52,size*0.36)
    ctx.lineTo(size*0.65,size*0.48)
    ctx.stroke()
    return ctx.getImageData(0,0,size,size)
  }
  chrome.action.setIcon({imageData:{16:draw(16),32:draw(32)}})
}

chrome.storage.local.get(['pluginStatus']).then(s=>{
  try{ setIconTheme(s.pluginStatus==='TOPMOST') }catch(e){ console.warn('icon set failed', e) }
})
